#include"Util.hpp"

class ServerTcp
{
public:
    ServerTcp(uint16_t port, const std::string& ip = "")
        :sock_(-1)
        ,port_(port)
        ,ip_(ip)
    {}
    ~ServerTcp()
    {}

public:
    void init()
    {
        //1.创建socket
        sock_ = socket(AF_INET, SOCK_STREAM, 0);
        if(sock_ < 0)
        {
            logMessage(FATAL, "socket: %s", strerror(errno));
            exit(SOCKET_ERR);
        }
        logMessage(DEBUG, "socket: %s:%d", strerror(errno), sock_);

        //2.bind绑定
        //2.1 填充服务器信息
        struct sockaddr_in local; // 用户栈
        bzero(&local, sizeof local);

        local.sin_family = AF_INET;
        local.sin_port = htons(port_);
        ip_.empty() ? (local.sin_addr.s_addr = INADDR_ANY) : (inet_aton(ip_.c_str(), &local.sin_addr)); 

        //2.2本地socket信息, 写入sock_对应的内核区域
        if(bind(sock_, (const struct sockaddr*)&local, sizeof local))
        {
            logMessage(FATAL, "bind: %s", strerror(errno));
            exit(BIND_ERR);
        }
        logMessage(DEBUG, "bind: %s:%d", strerror(errno), sock_);

        //3.监听socket, 为何要监听呢? tcp 是面向连接的
        if(listen(sock_, 5) < 0)
        {
            logMessage(FATAL, "listen: %s", strerror(errno));
            exit(LISTEN_ERR);
        }
        logMessage(DEBUG, "listen: %s:%d", strerror(errno), sock_);
        
        //允许别人连接你了
    }
    


private:
    int sock_; // sock
    uint16_t port_; // port
    std::string ip_; // ip
};